//
//  PEFirmwareUpgradeVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/3.
//

#import "RHLocalFirmwareUpgradeVC.h"
#import "RHNavigationController.h"

@interface RHLocalFirmwareUpgradeVC ()
@property (nonatomic ,strong) UIProgressView *progressView;

@property (nonatomic ,strong) QMUILabel *downloadTitleLab;

@property (nonatomic ,strong) QMUILabel *progressLab;

@property (nonatomic ,strong) UIImageView *stepImg;

@property (nonatomic ,strong) QMUIButton *upgradeBtn;

@property (nonatomic ,strong) QMUILabel *tipsLab;

@property (nonatomic ,strong) NSURLSessionDownloadTask *downloadTask;

@property (nonatomic ,strong) NSData *resumeData;

@property (nonatomic ,copy) NSURL *filePath;

@property (nonatomic ,strong) NSArray *firmwareArr;
@end

@implementation RHLocalFirmwareUpgradeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"固件升级".rh_localized;
    [self setupUI];
    [self checkFirmware];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [(RHNavigationController*)self.navigationController setBackgoundClear:YES titleColor:nil] ;
   
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [(RHNavigationController*)self.navigationController setBackgoundClear:NO titleColor:nil];
}

-(void)setupUI
{
    [self.view setGradientBackgroundWithColors:@[kColorRGBA(208, 251, 217,1),kColorRGBA(235, 251, 241, 1),kColorRGBA(212, 253, 230,1)] locations:@[@(0),@(0.5),@(1)] startPoint:CGPointMake(0.5, 0) endPoint:CGPointMake(0.5, 1)];
 
    
    kWeakSelf;
    UIScrollView *scrollView = [[UIScrollView alloc]init];
    scrollView.backgroundColor = UIColor.clearColor;
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    UIView *contentView = kView;
    contentView.backgroundColor = UIColor.clearColor;
    contentView.layer.cornerRadius = 8;
    [scrollView addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        make.width.offset(kUI_WINDOW_W);
        make.height.greaterThanOrEqualTo(@(kUI_WINDOW_H-kNavHeight));
    }];
    
    UIImageView *stepImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"firmware_download"]];
    stepImg.contentMode = UIViewContentModeScaleAspectFill;
    [contentView addSubview:stepImg];
    self.stepImg = stepImg;
    [stepImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.mas_offset(kNavHeight+50);
        make.width.offset(kScaleW(151));
        make.height.offset(kScaleW(144));
    }];
    
    QMUILabel *downloadTitleLab = [QMUILabel labelWithFont:kSYSTEMFONT(12) textColor:kColorRGBA(63, 68, 67, 0.8)];
    downloadTitleLab.text = [NSString stringWithFormat:@"%@:",@"下载进度".rh_localized];
    [contentView addSubview:downloadTitleLab];
    self.downloadTitleLab = downloadTitleLab;
    [downloadTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(stepImg.mas_bottom).offset(50);
        make.left.mas_offset(45);
    }];
    
    QMUILabel *progressLab = [QMUILabel labelWithFont:kBOLDSYSTEMFONT(16) textColor:kRGB(253, 198, 91)];
    progressLab.text = @"0%";
    [contentView addSubview:progressLab];
    self.progressLab = progressLab;
    [progressLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(downloadTitleLab);
        make.left.equalTo(downloadTitleLab.mas_right).offset(5);
    }];
    
    _progressView = [[UIProgressView alloc]init];
    _progressView.progressTintColor = kRGB(252, 226, 105);
    _progressView.trackTintColor = UIColor.whiteColor;
    
    [contentView addSubview:_progressView];
    for (UIImageView * imageview in _progressView.subviews) {
        imageview.layer.cornerRadius = 5;
        imageview.clipsToBounds = YES;
    }
    [_progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(45);
        make.right.mas_offset(-45);
        make.top.equalTo(progressLab.mas_bottom).offset(10);
        make.height.offset(10);
    }];
    
    QMUILabel *versionLab = [QMUILabel labelWithFont:kSYSTEMFONT(16) textColor:kRGB(63, 68, 67) textAligment:NSTextAlignmentCenter];
    versionLab.text = [NSString stringWithFormat:@"%@ %@",self.firmwareModel.endpoint,self.firmwareModel.firmwareNumber];
    versionLab.numberOfLines = 0;
    [contentView addSubview:versionLab];
    [versionLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(weakSelf.progressView.mas_bottom).offset(25);
    }];
    
    QMUILabel *tipsLab = [QMUILabel labelWithFont:kSYSTEMFONT(12) textColor:kRGB(63, 68, 67) textAligment:NSTextAlignmentCenter];
    tipsLab.numberOfLines = 0;
    tipsLab.text = @"正在下载设备固件，请勿离开设备，保持手机网络正常".rh_localized;
    [contentView addSubview:tipsLab];
    self.tipsLab = tipsLab;
    [tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.top.equalTo(versionLab.mas_bottom).offset(10);
    }];
    
    QMUILabel *tipsLab2 = [[QMUILabel alloc] init];
    [tipsLab2 setTextAlignment:NSTextAlignmentLeft];
    [tipsLab2 setTextColor:kColorRGBA(63, 68, 67, 0.6)];
    [tipsLab2 setFont:[UIFont systemFontOfSize:12]];
    [tipsLab2 setNumberOfLines:0];
    tipsLab2.text = @"提示：升级前请保持APP和设备蓝牙链接正常，手机和设备电量充足。整个升级过程大概需要2分钟，期间请勿操作和使用设备，否则可能有安全风险。".rh_localized;
    tipsLab2.qmui_lineHeight = 20;
    [contentView addSubview:tipsLab2];
    [tipsLab2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    QMUIButton *upgradeBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [upgradeBtn setTitle:@"升级".rh_localized forState:UIControlStateNormal];
    [upgradeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    upgradeBtn.titleLabel.font = kSYSTEMFONT(16);
    [upgradeBtn setGradientBackgroundWithColors:@[kRGB(106, 215, 133),kRGB(94, 203, 183)] orientation:GradientOrientationLeftToRight];
    [upgradeBtn setCornerRadius:8];
    self.upgradeBtn = upgradeBtn;
    [contentView addSubview:upgradeBtn];
    
    
    [upgradeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(50);
        make.bottom.equalTo(tipsLab2.mas_top).offset(-10);
    }];
    
    [[upgradeBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf buttonAction];
    }];
}


-(void)checkFirmware
{
    NSString *firmwareName = [NSString stringWithFormat:@"%@.zip",self.firmwareModel.firmwareId];
    if([self.firmwareArr containsObject:firmwareName]){
        NSLog(@"----->已存在此固件,直接升级");
        [self uploadFileToBlueDevice:self.filePath];
    }else{
        NSLog(@"----->本地不存在此固件,从服务器下载");
        [self getFirmwareDownloadURL];
    }
}


//获取固件下载地址
-(void)getFirmwareDownloadURL
{
    [QMUITips showLoading:@"获取固件地址".rh_localized inView:self.view];
    NSMutableDictionary *updateDic = [NSMutableDictionary dictionary];
    [updateDic setValue:self.firmwareModel.endpoint forKey:@"endpoint"];
    [updateDic setValue:[self.firmwareModel.sn firstObject][@"sn"] forKey:@"sn"];
    
    NSDictionary *para = @{@"deviceId":@"DC10001XF1010050",
                           @"password":@"123456",
                           @"updateDtoList":@[updateDic]
    };
    
    //获取最新固件列表
    [BaseModel startWithCompletionAPIKey:D_getDownLoadUrl argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            if([request.responseJSONObject[@"data"] isKindOfClass:[NSArray class]]){
                NSDictionary *dic = [request.responseJSONObject[@"data"] firstObject];
               
                [self downloadFirmwareWithUrl:dic[@"firmwareUrl"]];
            }
            
                
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
    
}

-(void)buttonAction
{
    //没有获取到下载地址
    if(self.downloadTask==nil){
        [self getFirmwareDownloadURL];
    }else{
        //有任务
        if([self.upgradeBtn.titleLabel.text isEqualToString:@"暂停".rh_localized]){
            [self.upgradeBtn setTitle:@"继续".rh_localized forState:UIControlStateNormal];
            kWeakSelf;
            [self.downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
                weakSelf.resumeData = resumeData;
            }];
        }else if([self.upgradeBtn.titleLabel.text isEqualToString:@"继续".rh_localized]){
            [self.upgradeBtn setTitle:@"暂停".rh_localized forState:UIControlStateNormal];
            AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
           
           self.downloadTask = [manger downloadTaskWithResumeData:self.resumeData progress:^(NSProgress * _Nonnull downloadProgress) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString *progress = [NSString stringWithFormat:@"%.0f%%",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount *100];
                    self.downloadTitleLab.text = [NSString stringWithFormat:@"%@:",@"下载进度".rh_localized];
                    [self.upgradeBtn setTitle:@"暂停".rh_localized forState:UIControlStateNormal];
                    self.tipsLab.text = @"正在下载设备固件，请勿离开设备，保持手机网络正常".rh_localized;
                    self.progressLab.text = progress;
                    self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
                });
            } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
                return self.filePath;
            } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
                if(error){
                    NSLog(@"---->下载失败:%@",error);
                }else{
                    //蓝牙升级
                    [self uploadFileToBlueDevice:filePath];
                }
            }];
            [self.downloadTask resume];
        }
          
    }
}

//下载固件
-(void)downloadFirmwareWithUrl:(NSString*)file_url
{
    NSURL *url = [NSURL URLWithString:file_url];
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    self.downloadTask = [manger downloadTaskWithRequest:[NSURLRequest requestWithURL:url] progress:^(NSProgress * _Nonnull downloadProgress) {
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *progress = [NSString stringWithFormat:@"%.0f%%",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount *100];
            self.downloadTitleLab.text = [NSString stringWithFormat:@"%@:",@"下载进度".rh_localized];
            [self.upgradeBtn setTitle:@"暂停".rh_localized forState:UIControlStateNormal];
            self.tipsLab.text = @"正在下载设备固件，请勿离开设备，保持手机网络正常".rh_localized;
            self.progressLab.text = progress;
            self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        });
       
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.upgradeBtn setTitle:@"暂停".rh_localized forState:UIControlStateNormal];
        });
        
        
        return self.filePath;
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        if(error){
            NSLog(@"---->下载失败:%@",error);
        }else{
            //蓝牙升级
            [self uploadFileToBlueDevice:filePath];
        }
       
        
    }] ;
    [self.downloadTask resume];
    
    
}

//固件升级
-(void)uploadFileToBlueDevice:(NSURL*)filePath
{
    self.stepImg.image = [UIImage imageNamed:@"firmware_upload"];
    self.downloadTitleLab.text = [NSString stringWithFormat:@"%@:",@"升级进度".rh_localized];
    self.progressLab.text = @"0%";
    self.progressView.progress = 0;
    [self.upgradeBtn setTitle:@"固件升级中".rh_localized forState:UIControlStateNormal];
    self.tipsLab.text = @"正在升级设备固件，请勿操作此页面，等待设备升级完成".rh_localized;
}


-(NSURL *)filePath
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *firmwareFold = [documentPath stringByAppendingPathComponent:@"Firmware"];
    if(![[NSFileManager defaultManager] isExecutableFileAtPath:firmwareFold]){
        [[NSFileManager defaultManager] createDirectoryAtPath:firmwareFold withIntermediateDirectories:YES attributes:nil error:nil];
    };
    NSString *downloadURL = [NSString stringWithFormat:@"%@/%@.zip",firmwareFold,self.firmwareModel.firmwareId];
    NSURL *fileUrl = [NSURL fileURLWithPath:downloadURL];
    NSLog(@"----->固件存放路径:%@",downloadURL);
    
    return fileUrl;
}

-(NSArray *)firmwareArr
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *firmwareFold = [documentPath stringByAppendingPathComponent:@"Firmware"];
    NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:firmwareFold error:nil];
    
    return files;
}
@end
